package token

import (
	"github.com/gogf/gf/net/ghttp"
	"go-middle/library/response"
)

// Init 验证token中间件
func Init(r *ghttp.Request) {
	id := r.Header.Get("token")
	if id != "" {
		_, err := Auth(id)
		if err != nil {
			response.StatusCode(r, 403, err.Error())
		}
		_ = r.Session.SetId(id)
	} else {
		fn := func() {
			info, _ := Generate()
			r.Session = info.Session
		}
		id = r.Cookie.GetSessionId()
		if id == "" {
			fn()
		}else {
			_, err := Auth(id)
			if err != nil {
				fn()
			}
		}
	}
	r.Middleware.Next()
}
